<template>
  <div class="home-page">
    <div class="header-box">
      <el-button
        style="background-color: #43cf7c; color: #fff; margin-left: 10px"
        @click="searchDialogVisible = true"
        >排名查询</el-button
      >
      <el-button
        style="background-color: #43cf7c; color: #fff; margin-left: 10px"
        @click="getPollutionMap"
        >获取污染数据</el-button
      >
      <el-button
        style="background-color: #43cf7c; color: #fff; margin-left: 10px"
        @click="dialogVisible = true"
        >数据导出</el-button
      >
      <!-- <el-button
        style="
          background-color: rgb(37, 141, 231);
          color: #fff;
          margin-left: 10px;
        "
        @click="getTableData('恶臭监测数据')"
        >恶臭监测数据</el-button
      >
      <el-button
        style="
          background-color: rgb(37, 141, 231);
          color: #fff;
          margin-left: 10px;
        "
        @click="getTableData('Voc监测数据')"
        >Voc监测数据</el-button
      > -->
      <!-- <el-button
        style="
          background-color: #4356cf;
          color: #fff;
          position: absolute;
          right: 10px;
        "
        @click="loginOut"
        >退出登录</el-button
      > -->
    </div>
    <el-container>
      <el-aside width="17vw">
        <ranking ref="rankingRef" @getRankingUrl="getRankingUrl" />
      </el-aside>
      <el-main>
        <div id="cesiumContainer">
          <div
            class="tree"
            ref="tree"
            :style="{ right: stretch ? '-12%' : '0' }"
          >
            <div class="tree-item" v-for="item in pointTypeList">
              <el-checkbox
                v-model="item.isShow"
                style="color: #fff"
                @change="handleTypeChange"
                >{{ item.name }}</el-checkbox
              >
              <span
                class="item-col"
                :style="{ backgroundColor: item.color }"
              ></span>
            </div>
            <div class="stretchBot" @click="stretch = !stretch">
              <i class="el-icon-arrow-left" v-if="stretch"></i>
              <i class="el-icon-arrow-right" v-else></i>
            </div>
          </div>
        </div>
        <div class="footer">
          <div class="footer-left">
            <div class="left">
              <div class="main">
                <dd class="title">{{ siteName }}实时AQI</dd>
                <dd class="time">{{ dateTime }}</dd>
                <dd>
                  <span class="value">{{ aqiValue }}</span
                  ><span class="grade">{{ airQualityType }}</span>
                </dd>
              </div>
              <img src="../assets/image/site_bg.png" alt="" srcset="" />
            </div>
            <div class="right">
              <div
                class="item"
                v-for="(item, key) in gasObj"
                :key="key"
                v-show="item.value !== null"
              >
                <div class="echarts" :id="item.key"></div>
                <div
                  class="over-pollutant"
                  v-show="primaryPollutant == item.key"
                >
                  首要污染物
                </div>
              </div>
            </div>
          </div>
          <div class="footer-right">
            <img src="../assets/image/yun.png" alt="" srcset="" />
            <dd>
              <span style="color: #9c9a99">温度</span
              ><span style="font-weight: 700">{{ dataInfo.a01001 }}℃</span>
            </dd>
            <dd>
              <span style="color: #9c9a99">湿度</span
              ><span style="font-weight: 700">{{ dataInfo.a01002 }}%RH</span>
            </dd>
            <dd>
              <span style="color: #9c9a99">风向风速</span
              ><span style="font-weight: 700"
                >{{ dataInfo.a01008 }}° {{ dataInfo.a01007 }}m/s</span
              >
            </dd>
          </div>
        </div>
      </el-main>
    </el-container>
    <div class="infoPop" v-show="infoPopShow" v-drag>
      <div class="title-name">实时数据</div>
      <div class="close el-icon-close" @click="closeInfoPop"></div>
      <div class="dit">
        <p class="time" style="width: 50%; padding-left: 12px">
          数据时间：{{ dataInfo.dataTime }}
        </p>
      </div>
      <div class="package">
        <div class="left">
          <div class="form">
            <div class="row">
              <p class="text">O3：{{ dataInfo.a05024 }} μg/m³</p>
              <p class="text">NO2：{{ dataInfo.a21004 }} μg/m³</p>
            </div>
            <div class="row">
              <p class="text">CO：{{ dataInfo.a21005 }} μg/m³</p>
              <p class="text">SO2：{{ dataInfo.a21026 }} μg/m³</p>
            </div>
            <div class="row">
              <p class="text">PM10：{{ dataInfo.a34002 }} μg/m³</p>
              <p class="text">PM2.5：{{ dataInfo.a34004 }} μg/m³</p>
            </div>
            <div class="row">
              <p class="text">总悬浮颗粒：{{ dataInfo.a34001 }} μg/m³</p>
              <p class="text">VOCs：{{ dataInfo.a99054 }} mg/m³</p>
            </div>
            <div class="row">
              <p class="text">温度：{{ dataInfo.a01001 }} ℃</p>
              <p class="text">湿度：{{ dataInfo.a01002 }} %RH</p>
            </div>
            <div class="row">
              <p class="text">风速：{{ dataInfo.a01007 }} m/s</p>
              <p class="text">风向：{{ dataInfo.a01008 }} °</p>
            </div>
            <div class="row">
              <p class="text">
                <el-button @click="showHistory">查看历史数据</el-button>
              </p>
              <p class="text">
                <el-button @click="siteInfoShow = true">查看站点信息</el-button>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="infoPop" style="top: 10%" v-show="siteInfoShow" v-drag>
      <div class="title-name">站点信息</div>
      <div class="close el-icon-close" @click="siteInfoShow = false"></div>
      <div class="package">
        <div class="left">
          <div class="form">
            <div class="row">
              <p class="text">站点名称：{{ siteInfo.name }}</p>
              <p class="text">
                站点类型：{{ pointTypeList[Number(siteInfo.type)].name }}
              </p>
            </div>
            <div class="row">
              <p class="text">所在地址：{{ siteInfo.address }}</p>
              <p class="text">区域名称：{{ siteInfo.areaName }}</p>
            </div>
            <div class="row">
              <p class="text">经度：{{ siteInfo.longitude }}</p>
              <p class="text">纬度：{{ siteInfo.latitude }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :visible.sync="searchDialogVisible"
      title="排名查询"
      width="1000px"
      class="dialog"
    >
      <div class="search-box">
        <span> 时间类型：</span>
        <el-select
          v-model="reportType"
          placeholder="请选择类型"
          style="width: 6vw"
        >
          <el-option label="小时" :value="1"></el-option>
          <el-option label="日" :value="2"></el-option>
          <el-option label="周" :value="3"></el-option>
          <el-option label="月" :value="4"></el-option>
          <el-option label="年" :value="5"></el-option>
        </el-select>
        <span> 排名参数：</span>
        <el-select
          v-model="orderBy"
          placeholder="请选择排名参数"
          style="width: 8vw"
        >
          <el-option label="pm2.5" value="pm25"></el-option>
          <el-option label="pm10" value="pm10"></el-option>
          <el-option label="so2" value="so2"></el-option>
          <el-option label="no2" value="no2"></el-option>
          <el-option label="co" value="co"></el-option>
          <el-option label="o3" value="o3"></el-option>
          <el-option label="综合指数" value="total"></el-option>
        </el-select>
        <span> 时间范围：</span>
        <el-date-picker
          v-model="searchDateTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        >
        </el-date-picker>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="searchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="getRankingData">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisible"
      title="站点列表"
      width="1200px"
      class="dialog"
    >
      <div class="search-box">
        <span> 导出数据时间范围：</span>
        <el-date-picker
          v-model="exportTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        >
        </el-date-picker>
        <span> 站点名称：</span>
        <el-input
          v-model="exportFilterByName"
          placeholder="请选择站点名称"
          style="width: 180px"
          clearable
        ></el-input>
        <span> 站点类型：</span>
        <el-select
          v-model="exportPointType"
          placeholder="请选择站点类型"
          clearable
        >
          <el-option
            v-for="item in pointTypeList"
            :label="item.name"
            :value="item.name"
          ></el-option>
        </el-select>
      </div>
      <el-table
        :data="tableData"
        :border="true"
        :stripe="true"
        ref="multipleTable"
        style="width: 100%; height: 50vh; margin: 15px 0"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          prop="name"
          label="站点名称"
          sortable
        ></el-table-column>
        <el-table-column prop="type" label="站点类型" sortable>
          <template slot-scope="scope">{{
            pointTypeList[Number(scope.row.type)].name
          }}</template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="所在地址"
          width="255"
        ></el-table-column>
        <el-table-column
          prop="areaName"
          label="区域名称"
          sortable
        ></el-table-column>
        <el-table-column prop="longitude" label="经度"></el-table-column>
        <el-table-column prop="latitude" label="纬度"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="exportExcel" :loading="exportLoading"
          >导出</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="monitorDialogVisible"
      :title="monitorTitle"
      width="80vw"
      class="dialog"
      top="10vh"
    >
      <div class="search-box">
        <span> 监测数据时间：</span>
        <el-date-picker
          v-model="monitorDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="true"
        >
        </el-date-picker>
        <span v-show="monitorTitle === 'Voc监测数据'"> 监测点位：</span>
        <el-select
          v-model="monitorPoint"
          placeholder="请选择监测点位"
          clearable
          v-show="monitorTitle === 'Voc监测数据'"
        >
          <el-option
            v-for="item in monitorVocsOptions"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          style="background-color: #43cf7c; color: #fff; margin-left: 10px"
          @click="getTableData(monitorTitle)"
          >查询</el-button
        >
      </div>
      <el-table
        :data="monitorTableData"
        :border="true"
        :stripe="true"
        style="width: 100%; margin: 15px 0"
        max-height="700"
      >
        <el-table-column
          :prop="item.prop"
          :label="item.label"
          v-for="item in monitorHeader"
        ></el-table-column>
      </el-table>
      <div class="el-pagination-box" style="margin-bottom: 10px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[50, 100, 200, 500]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="monitorTotal"
        >
        </el-pagination>
      </div>
    </el-dialog>
    <pollution ref="pollutionRef" :areaCode="areaCode" />
    <history-data ref="historyDataRef" :code="code" />
  </div>
</template>
<script>
import * as echarts from "echarts";
import Ranking from "@/components/Ranking.vue";
import Pollution from "@/components/Pollution.vue";
import HistoryData from "@/components/HistoryData.vue";
import axios from "axios";
import qs from "qs";
const dayjs = require("dayjs");
const XLSX = require("xlsx");
let viewer;
export default {
  name: "Home",
  components: {
    ranking: Ranking,
    pollution: Pollution,
    "history-data": HistoryData,
  },
  data() {
    return {
      reportType: 1,
      orderBy: "total",
      searchDateTime: "",
      exportTime: "",
      order: "asc",
      dateTime: "",
      aqiValue: "58",
      airQualityType: "良",
      gasObj: [
        { key: "PM2.5", value: 0 },
        { key: "PM10", value: 0 },
        { key: "CO", value: 0 },
        { key: "SO2", value: 0 },
        { key: "O3", value: 0 },
        { key: "NO2", value: 0 },
      ],
      primaryPollutant: "",
      gasCount: 0,
      siteName: "中山市",
      pointList: [],
      pmUrl: "/ranking/getInProvinceRank",
      dataInfo: {
        dataTime: "",
        a05024: "",
        a21004: "",
        a21005: "",
        a21026: "",
        a34002: "",
        a34004: "",
        a01001: "",
        a01002: "",
        a01007: "",
        a01008: "",
        a34001: "",
        a99054: "",
      },
      siteInfo: {
        name: "",
        type: "",
        address: "",
        areaName: "",
        latitude: "",
        longitude: "",
      },
      infoPopShow: false,
      siteInfoShow: false,
      isFirstLoad: false,
      areaCode: "",
      code: "",
      stretch: false,
      pointTypeList: [
        {
          name: "国控点",
          color: "rgb(37,141,231)",
          isShow: false,
        },
        {
          name: "省控点",
          color: "rgb(218,75,95)",
          isShow: false,
        },
        {
          name: "市控",
          color: "rgb(225,186,25)",
          isShow: false,
        },
        {
          name: "中山市微站",
          color: "rgb(51,176,84)",
          isShow: false,
        },
        {
          name: "火炬区微站",
          color: "rgb(26,178,174)",
          isShow: true,
        },
        {
          name: "摄像头",
          color: "rgb(255,0,255)",
          isShow: false,
        },
      ],
      dialogVisible: false,
      selectedRows: [],
      exportLoading: false,
      searchDialogVisible: false,
      exportFilterByName: "",
      exportPointType: "",
      monitorDialogVisible: false,
      monitorData: [],
      monitorTitle: "",
      monitorVocsOptions: [
        {
          value: "百灵生物科技",
          label: "百灵生物科技",
          children: [
            {
              value: "2023.3.1-4.30数据监控监测项目",
              label: "2023.3.1-4.30数据监控监测项目",
            },
            {
              value: "2023.5.1-6.30数据监控监测项目",
              label: "2023.5.1-6.30数据监控监测项目",
            },
            {
              value: "2023.7.1-8.31数据监控监测项目",
              label: "2023.7.1-8.31数据监控监测项目",
            },
            {
              value: "2023.9.1-10.31数据监控监测项目",
              label: "2023.9.1-10.31数据监控监测项目",
            },
            {
              value: "2023.11.1-12.31数据监控监测项目",
              label: "2023.11.1-12.31数据监控监测项目",
            },
            {
              value: "2024.1.1-2.29数据监控监测项目",
              label: "2024.1.1-2.29数据监控监测项目",
            },
          ],
        },
        {
          value: "迪爱生",
          label: "迪爱生",
          children: [
            {
              value: "2023.3.1-4.30数据监控监测项目",
              label: "2023.3.1-4.30数据监控监测项目",
            },
            {
              value: "2023.5.1-6.30数据监控监测项目",
              label: "2023.5.1-6.30数据监控监测项目",
            },
            {
              value: "2023.7.1-8.31数据监控监测项目",
              label: "2023.7.1-8.31数据监控监测项目",
            },
            {
              value: "2023.9.1-10.31数据监控监测项目",
              label: "2023.9.1-10.31数据监控监测项目",
            },
            {
              value: "2023.11.1-12.31数据监控监测项目",
              label: "2023.11.1-12.31数据监控监测项目",
            },
            {
              value: "2024.1.1-2.29数据监控监测项目",
              label: "2024.1.1-2.29数据监控监测项目",
            },
          ],
        },
        {
          value: "火炬水务公司",
          label: "火炬水务公司",
          children: [
            {
              value: "2023.3.1-4.30数据监控监测项目",
              label: "2023.3.1-4.30数据监控监测项目",
            },
            {
              value: "2023.5.1-6.30数据监控监测项目",
              label: "2023.5.1-6.30数据监控监测项目",
            },
            {
              value: "2023.7.1-8.31数据监控监测项目",
              label: "2023.7.1-8.31数据监控监测项目",
            },
            {
              value: "2023.9.1-10.31数据监控监测项目",
              label: "2023.9.1-10.31数据监控监测项目",
            },
            {
              value: "2023.11.1-12.31数据监控监测项目",
              label: "2023.11.1-12.31数据监控监测项目",
            },
            {
              value: "2024.1.1-2.29数据监控监测项目",
              label: "2024.1.1-2.29数据监控监测项目",
            },
          ],
        },
        {
          value: "联成化工",
          label: "联成化工",
          children: [
            {
              value: "2023.3.1-4.30数据监控监测项目",
              label: "2023.3.1-4.30数据监控监测项目",
            },
            {
              value: "2023.5.1-6.30数据监控监测项目",
              label: "2023.5.1-6.30数据监控监测项目",
            },
            {
              value: "2023.7.1-8.31数据监控监测项目",
              label: "2023.7.1-8.31数据监控监测项目",
            },
            {
              value: "2023.9.1-10.31数据监控监测项目",
              label: "2023.9.1-10.31数据监控监测项目",
            },
            {
              value: "2023.11.1-12.31数据监控监测项目",
              label: "2023.11.1-12.31数据监控监测项目",
            },
            {
              value: "2024.1.1-2.29数据监控监测项目",
              label: "2024.1.1-2.29数据监控监测项目",
            },
          ],
        },
        {
          value: "美味鲜",
          label: "美味鲜",
          children: [
            {
              value: "2023.3.1-4.30数据监控监测项目",
              label: "2023.3.1-4.30数据监控监测项目",
            },
            {
              value: "2023.5.1-6.30数据监控监测项目",
              label: "2023.5.1-6.30数据监控监测项目",
            },
            {
              value: "2023.7.1-8.31数据监控监测项目",
              label: "2023.7.1-8.31数据监控监测项目",
            },
            {
              value: "2023.9.1-10.31数据监控监测项目",
              label: "2023.9.1-10.31数据监控监测项目",
            },
            {
              value: "2023.11.1-12.31数据监控监测项目",
              label: "2023.11.1-12.31数据监控监测项目",
            },
            {
              value: "2024.1.1-2024.2.29数据监控监测项目",
              label: "2024.1.1-2024.2.29数据监控监测项目",
            },
          ],
        },
        {
          value: "天彩包装",
          label: "天彩包装",
          children: [
            {
              value: "2023.3.1-4.30数据监控监测项目",
              label: "2023.3.1-4.30数据监控监测项目",
            },
            {
              value: "2023.5.1-6.30数据监控监测项目",
              label: "2023.5.1-6.30数据监控监测项目",
            },
            {
              value: "2023.7.1-8.31数据监控监测项目",
              label: "2023.7.1-8.31数据监控监测项目",
            },
            {
              value: "2023.9.1-10.31数据监控监测项目",
              label: "2023.9.1-10.31数据监控监测项目",
            },
            {
              value: "2023.11.1-12.31数据监控监测项目",
              label: "2023.11.1-12.31数据监控监测项目",
            },
            {
              value: "2024.1.1-2.29数据监控监测项目",
              label: "2024.1.1-2.29数据监控监测项目",
            },
          ],
        },
        {
          value: "祥丰电子（废弃排放口14）",
          label: "祥丰电子（废弃排放口14）",
          children: [
            {
              value: "2023.3.1-4.30数据监控监测项目-排放口14",
              label: "2023.3.1-4.30数据监控监测项目-排放口14",
            },
            {
              value: "2023.5.1-6.30数据监控监测项目-排放口14",
              label: "2023.5.1-6.30数据监控监测项目-排放口14",
            },
            {
              value: "2023.7.1-8.31数据监控监测项目-排放口14",
              label: "2023.7.1-8.31数据监控监测项目-排放口14",
            },
            {
              value: "2023.9.1-10.31数据监控监测项目-排放口14",
              label: "2023.9.1-10.31数据监控监测项目-排放口14",
            },
            {
              value: "2023.11.1-12.31数据监控监测项目-排放口14",
              label: "2023.11.1-12.31数据监控监测项目-排放口14",
            },
            {
              value: "2024.1.1-2.29数据监控监测项目-排放口14",
              label: "2024.1.1-2.29数据监控监测项目-排放口14",
            },
          ],
        },
        {
          value: "祥丰电子（废弃排放口6）",
          label: "祥丰电子（废弃排放口6）",
          children: [
            {
              value: "2023.3.1-4.30数据监控监测项目-排放口6",
              label: "2023.3.1-4.30数据监控监测项目-排放口6",
            },
            {
              value: "2023.5.1-6.30数据监控监测项目-排放口6",
              label: "2023.5.1-6.30数据监控监测项目-排放口6",
            },
            {
              value: "2023.7.1-8.31数据监控监测项目-排放口6",
              label: "2023.7.1-8.31数据监控监测项目-排放口6",
            },
            {
              value: "2023.9.1-10.31数据监控监测项目-排放口6",
              label: "2023.9.1-10.31数据监控监测项目-排放口6",
            },
            {
              value: "2023.11.1-12.31数据监控监测项目-排放口6",
              label: "2023.11.1-12.31数据监控监测项目-排放口6",
            },
            {
              value: "2024.1.1-2.29数据监控监测项目-排放口6",
              label: "2024.1.1-2.29数据监控监测项目-排放口6",
            },
          ],
        },
      ],
      monitorPoint: "",
      monitorDate: null,
      monitorTableData: [],
      monitorHeader: [],
      currentPage: 1,
      pageSize: 50,
      monitorTotal: 0,
    };
  },
  computed: {
    tableData() {
      const type = this.pointTypeList.findIndex(
        (item) => item.name === this.exportPointType
      );
      return this.pointList.filter(
        (item) =>
          item.name.includes(this.exportFilterByName) &&
          (item.type === type + "" || type === -1)
      );
    },
  },
  mounted() {
    this.initMap();
    this.getPointList();
    this.dateTime =
      dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss").substring(0, 14) + "00";
    this.searchDateTime = [
      dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss").substring(0, 11) +
        "00:00:00",
      dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss").substring(0, 11) +
        "23:59:59",
    ];
    this.exportTime = [
      dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss").substring(0, 11) +
        "00:00:00",
      dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss").substring(0, 11) +
        "23:59:59",
    ];
    this.getRankingData();
  },
  methods: {
    initMap() {
      // 从Cesium ion账户中获取一个访问令牌
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5N2VlNjgyMC0wZmM3LTQ5Y2EtYTczZi1mZDM5MWJmMDI4NmIiLCJpZCI6NTQwODAsImlhdCI6MTYzNjI4NTM4NH0.bsr8ri-Wi-0_1RKoBLM9kpq3CyBMqufTgqtp0kGlS14";
      // 加入地形
      viewer = new Cesium.Viewer("cesiumContainer", {
        animation: false, //是否显示动画控件
        shouldAnimate: true,
        homeButton: false, //是否显示Home按钮
        fullscreenButton: false, //是否显示全屏按钮
        baseLayerPicker: false, //是否显示图层选择控件
        geocoder: false, //是否显示地名查找控件
        timeline: false, //是否显示时间线控件
        sceneModePicker: false, //是否显示投影方式控件
        navigationHelpButton: false, //是否显示帮助信息控件
        infoBox: false, //是否显示点击要素之后显示的信息
        requestRenderMode: true, //启用请求渲染模式
        selectionIndicator: false, //是否显示选取指示器组件
        scene3DOnly: false, //每个几何实例将只能以3D渲染以节省GPU内存
        sceneMode: 2, //初始场景模式 1 2D模式 2 2D循环模式 3 3D模式  Cesium.SceneMode
        terrainProvider: Cesium.createWorldTerrain(),
        imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
          url: "https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/WMTS",
          layer: "World_Imagery",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "GoogleMapsCompatible",
          maximumLevel: 19,
          credit: new Cesium.Credit("© Esri", "https://www.esri.com/"),
        }),
      });
      // 移除双击事件
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
      );
      // 删除默认地图
      // viewer.imageryLayers.removeAll();
      // 修改地图默认背景颜色
      // viewer.scene.globe.baseColor = Cesium.Color.WHITE
      // 隐藏版权
      viewer._cesiumWidget._creditContainer.style.display = "none";
      // let tdtLayer
      // // 矢量图
      // // tdtLayer = new Cesium.UrlTemplateImageryProvider({
      // //   url: "http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
      // //   minimumLevel: 3,
      // //   maximumLevel: 18,
      // // });
      // // viewer.imageryLayers.addImageryProvider(tdtLayer);
      // // 影像图
      // tdtLayer = new Cesium.UrlTemplateImageryProvider({
      //   url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
      //   minimumLevel: 3,
      //   maximumLevel: 18,
      // });
      // viewer.imageryLayers.addImageryProvider(tdtLayer);
      // //高德路网中文注记
      // tdtLayer = new Cesium.UrlTemplateImageryProvider({
      //   url: "http://webst02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8",
      //   minimumLevel: 3,
      //   maximumLevel: 18,
      // });
      // viewer.imageryLayers.addImageryProvider(tdtLayer);
      // 加载中山火炬地图
      // let token = "V0fOEkOhontwuX2BIblzcD5fA3UCTi1CwrIuGaFt6mvVFJv8fvBuGiWfCWiSYkIrHRTyvUos6hxLexTzBBXJPEtDS3js1kkxRIAM5zKpItti-KgYSyRLBupcDDMTQ1BKEBH7YlatoeWVh-vYS5oAG4UQEttZOPE3UTMepMr7OFR2yJHwgVRcGS7Fmuqc2-IGwFrtH_C5n8PXqEt5MDUQWb0kTPPDiZlTCwYDeD5GDaynp6CjO6xbptvC2t2AJ0n0"
      // viewer.imageryLayers.addImageryProvider(
      //   new Cesium.ArcGisMapServerImageryProvider({
      //     url: 'https://model.hycx-gd.cn/server/rest/services/ZhongShan/ZhongShanHuoJuGongYeQu20230308/MapServer' + "/export",
      //     token,
      //   })
      // );
      let handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
      // 鼠标点击左键事件
      handler.setInputAction((click) => {
        const pickedFeature = viewer.scene.pick(click.position);
        // 判断是否拾取到实例
        if (!Cesium.defined(pickedFeature) || !pickedFeature.id) {
          return;
        }
        this.isFirstLoad = true;
        console.log("左键单击事件:", pickedFeature);
        console.log("数据:", pickedFeature.id.properties);
        let code = pickedFeature.id.properties._code._value;
        let name = pickedFeature.id.properties._name._value;
        this.areaCode = pickedFeature.id.properties._areaCode._value;
        this.siteInfo.name = pickedFeature.id.properties._name._value;
        this.siteInfo.type = pickedFeature.id.properties._type._value;
        this.siteInfo.address = pickedFeature.id.properties._address._value;
        this.siteInfo.areaName = pickedFeature.id.properties._areaName._value;
        this.siteInfo.longitude = pickedFeature.id.properties._longitude._value;
        this.siteInfo.latitude = pickedFeature.id.properties._latitude._value;
        this.getData(code, name);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    getPointList() {
      this.$api.get("/station/listStation").then((res) => {
        if (!res.result) {
          return;
        }
        const filterPointList = res.result.filter(
          (item) => this.pointTypeList.find((v, i) => item.type == i)?.isShow
        );
        // 设置中心点
        const centerData =
          filterPointList.length > 0 ? filterPointList[0] : res.result[0];
        var centerLongitude = Number(centerData.longitude);
        var centerLatitude = Number(centerData.latitude);
        var centerHeight = 30000;
        var centerPosition = Cesium.Cartesian3.fromDegrees(
          centerLongitude,
          centerLatitude,
          centerHeight
        );
        viewer.camera.setView({
          destination: centerPosition,
          orientation: {
            heading: Cesium.Math.toRadians(0),
            pitch: Cesium.Math.toRadians(-90),
            roll: 0,
          },
        });
        this.pointList = res.result;
        this.getData(centerData.code, centerData.name);
        this.areaCode = centerData.areaCode;
      });
    },
    handleTypeChange() {
      this.addPoint();
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    exportExcel() {
      if (this.selectedRows.length === 0) {
        this.$message.error("请选择要导出的站点");
        return;
      }
      let params = this.selectedRows.reduce((pre, item) => {
        pre.push({
          code: item.code,
          startTime: dayjs(this.exportTime[0]).format("YYYY-MM-DD HH:mm:ss"),
          endTime: dayjs(this.exportTime[1]).format("YYYY-MM-DD HH:mm:ss"),
        });
        return pre;
      }, []);
      const loading = this.$loading({
        lock: true,
        text: "导出中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      // this.exportLoading = true;
      this.$api
        .post("/station/getStationRealDataToExcel", params, {
          responseType: "blob",
        })
        .then((res) => {
          // 创建 Blob 对象并生成下载链接
          const blob = new Blob([res], { type: "application/vnd.ms-excel" });
          const url = URL.createObjectURL(blob);
          console.log(url);
          // 创建一个链接并模拟点击，触发下载
          const link = document.createElement("a");
          link.href = url;
          // link.setAttribute('download', 'excel-export.xlsx'); // 指定下载文件名
          link.click();
        })
        .finally(() => {
          loading.close();
          this.exportLoading = false;
          this.dialogVisible = false;
          this.selectedRows = [];
          this.$refs.multipleTable.clearSelection();
        });
    },
    addPoint() {
      // 删除所有实体
      viewer.entities.removeAll();
      this.pointList.forEach((item) => {
        item.color =
          item.code == this.code
            ? "#000"
            : this.pointTypeList[Number(item.type)].color;
        let position = Cesium.Cartesian3.fromDegrees(
          Number(item.longitude),
          Number(item.latitude),
          0
        );
        viewer.entities.add({
          position,
          point: {
            pixelSize: 8,
            color: Cesium.Color.fromCssColorString("rgba(0,0,0,0)"),
            outlineColor: Cesium.Color.fromCssColorString("#fff"),
            outlineWidth: 1,
          },
          show: this.pointTypeList[Number(item.type)].isShow,
          properties: item,
        });
        viewer.entities.add({
          position,
          point: {
            pixelSize: 20,
            color: Cesium.Color.fromCssColorString(item.color),
            outlineColor: Cesium.Color.fromCssColorString("#fff"),
            outlineWidth: 0,
            shaderSize: 0.5,
          },
          show: this.pointTypeList[Number(item.type)].isShow,
          properties: item,
        });
        viewer.entities.add({
          position,
          point: {
            pixelSize: 30,
            color: Cesium.Color.fromCssColorString("rgba(0,0,0,0)"),
            outlineColor: Cesium.Color.fromCssColorString(item.color),
            outlineWidth: 2,
          },
          show: this.pointTypeList[Number(item.type)].isShow,
          properties: item,
          label: {
            text: item.name,
            font: "bold 16px sans-serif",
            fillColor: Cesium.Color.fromCssColorString(item.color),
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 5,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            pixelOffset: new Cesium.Cartesian2(0, 33),
          },
        });
      });
    },
    transformSheets(sheets) {
      let content = [];
      let tmplist = [];
      for (let key in sheets) {
        tmplist.push(XLSX.utils.sheet_to_json(sheets[key]).length);
        content.push(XLSX.utils.sheet_to_json(sheets[key]));
      }
      return content;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getTableData(this.monitorTitle);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTableData(this.monitorTitle);
    },
    async getTableData(type) {
      this.monitorTitle = type;
      try {
        let urlList = [];
        if (type === "恶臭监测数据") {
          urlList.push("/static/excel/stink.xlsx");
        } else {
          // 获取地址
          this.monitorPoint =
            this.monitorPoint || this.monitorVocsOptions[0].value;
          const selMonitor = this.monitorVocsOptions.find(
            (item) => item.value === this.monitorPoint
          );
          selMonitor.children.forEach((item) => {
            urlList.push(
              `/static/excel/vocs/${
                this.monitorPoint.includes("祥丰电子")
                  ? "祥丰电子（废弃排放口14和废弃排放口6）"
                  : this.monitorPoint
              }/${item.value}.xlsx`
            );
          });
        }
        // 获取数据
        this.monitorData = [];
        for (let i = 0; i < urlList.length; i++) {
          const item = urlList[i];
          const res = await axios.get(item, { responseType: "arraybuffer" });
          let data = new Uint8Array(res.data);
          let wb = XLSX.read(data, { type: "array" });
          let sheets = wb.Sheets;
          let tableData = this.transformSheets(sheets)[0];
          this.monitorData = this.monitorData.concat(
            i > 0 ? tableData.slice(3) : tableData
          );
        }
        const headeraData = this.monitorData[1];
        this.monitorHeader = [];
        if (type === "恶臭监测数据") {
          Object.keys(headeraData).forEach((item) => {
            this.monitorHeader.push({
              prop: item,
              label: item,
            });
          });
        } else {
          // 二级表头
          Object.keys(headeraData).forEach((key) => {
            if (headeraData[key] !== "生产设施工况标记") {
              this.monitorHeader.push({
                prop: key,
                label: headeraData[key],
              });
            }
          });
          // 三级表头
          let threeTableHeader = [];
          Object.keys(this.monitorData[3]).forEach((key) => {
            if (["累计流量", "实测值"].includes(this.monitorData[3][key])) {
              threeTableHeader.push({
                prop: key,
                label: this.monitorData[3][key],
              });
            }
          });
          console.log(this.monitorHeader, threeTableHeader);
          // 匹配真实数据key
          this.monitorHeader
            .filter((v, i) => i > 0)
            .forEach((item, index) => {
              item.prop = threeTableHeader[index].prop;
            });
        }
        console.log(
          "header:",
          this.monitorHeader,
          "\n\rdata:",
          this.monitorData
        );
        this.monitorData.splice(0, 4);
        if (this.monitorDate) {
          const startTime = new Date(this.monitorDate[0]).getTime();
          const endTime = new Date(this.monitorDate[1]).getTime();
          this.monitorData = this.monitorData.filter((item) => {
            const dateTime = new Date(
              item[
                this.monitorHeader[type === "恶臭监测数据" ? 1 : 0].prop
              ].substring(0, 10)
            ).getTime();
            return dateTime > startTime && dateTime < endTime;
          });
        }
        // 分页
        this.monitorTotal = this.monitorData.length;
        const startIndex = (this.currentPage - 1) * this.pageSize;
        const endIndex = startIndex + this.pageSize;
        this.monitorTableData = this.monitorData.slice(startIndex, endIndex);
        this.monitorDialogVisible = true;
      } catch (error) {
        console.log(error);
        this.$message.error("获取数据失败!");
      }
    },
    getData(codeList, name) {
      this.code = codeList;
      this.$api
        .get("/station/stationHourAndDayData", {
          params: { codeList, dataType: 1 },
        })
        .then((res) => {
          console.log(res);
          if (res.result.length == 0) {
            this.$message.error("该站点暂无数据！");
            return;
          }
          this.getRealTimeData(codeList);
          this.addPoint();
          this.siteName = name;
          this.gasCount = 0;
          let data = res.result[0];
          this.primaryPollutant = data.primaryPollutant;
          this.aqiValue = data.aqi == null ? "null" : data.aqi;
          this.airQualityType = data.airQualityType;
          this.gasObj.forEach((item) => {
            switch (item.key) {
              case "PM2.5":
                item.value = data["pm25"];
                break;
              case "PM10":
                item.value = data["pm10"];
                break;
              case "CO":
                item.value = data["co"];
                break;
              case "SO2":
                item.value = data["so2"];
                break;
              case "O3":
                item.value = data["o3"] ? data["o3"] : null;
                break;
              case "NO2":
                item.value = data["no2"];
                break;
              default:
                break;
            }
            this.gasCount += Number(item.value);
          });
          this.gasObj.forEach((item) => {
            this.createEcharts(item);
          });
        });
    },
    getRealTimeData(codeList) {
      this.infoPopShow = this.isFirstLoad;
      this.$api
        .get("/station//stationMonitorData", { params: { codeList } })
        .then((res) => {
          console.log("实时数据:", res);
          this.dataInfo.dataTime = res.result[0].dataTime;
          res.result.forEach((item) => {
            Object.keys(this.dataInfo).forEach((_item) => {
              if (item.signalCode == _item) {
                this.dataInfo[_item] = item.signalValue;
              }
            });
          });
        });
    },
    closeInfoPop() {
      this.infoPopShow = false;
      this.siteInfoShow = false;
    },
    getRankingUrl(url) {
      this.pmUrl = url;
      this.getRankingData();
    },
    getRankingData() {
      this.searchDialogVisible = false;
      let params = {
        stime: dayjs(this.searchDateTime[0]).format("YYYY-MM-DD HH:mm:ss"),
        etime: dayjs(this.searchDateTime[1]).format("YYYY-MM-DD HH:mm:ss"),
        order: this.order,
        orderBy: this.orderBy,
        reportType: this.reportType,
      };
      console.log(params);
      this.$api.get(this.pmUrl, { params }).then((res) => {
        this.$refs.rankingRef.getData(res.result, params);
      });
    },
    showHistory() {
      this.$refs.historyDataRef.showDialog();
    },
    getPollutionMap() {
      this.$refs.pollutionRef.showDialog();
    },
    createEcharts(data) {
      let fontColor =
        data.key == this.primaryPollutant ? "rgb(230,230,50)" : "rgb(0,228,0)";
      let chartContainer = document.getElementById(data.key);
      let chart = echarts.init(chartContainer);
      let options = {
        title: {
          text: data.key,
          textStyle: {
            color: fontColor,
            fontSize: 16,
          },
          left: "center",
          top: "10%",
        },
        series: [
          {
            type: "pie",
            radius: ["70%", "55%"],
            label: {
              show: true,
              position: "center",
              formatter: data.value + "",
              textStyle: {
                color: "#333",
                fontSize: 16,
              },
            },
            silent: true,
            color: [fontColor, "rgb(235,235,235)"],
            data: [
              { value: data.value, name: data.key },
              { value: this.gasCount, name: "总数" },
            ],
          },
        ],
      };
      chart.setOption(options);
    },
    loginOut() {
      this.$confirm("确认退出登录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          setTimeout(() => {
            this.$router.push("/login");
            window.localStorage.setItem("token", "");
          }, 1000);
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="less">
.home-page {
  width: 100%;
  height: 100%;
  background-color: rgb(237, 245, 249);
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
  .search-box {
    span {
      margin-left: 10px;
    }

    .el-button {
      width: 100px;
      height: 40px;
      margin-left: 20px;
      color: #fff;
      border-radius: 5px;

      span {
        margin: 0;
      }
    }
  }

  .el-dialog .el-dialog__body {
    padding: 10px 20px;
  }

  .header-box {
    // position: absolute;
    // top: 10px;
    // left: 20px;
    width: 100%;
    height: 5vh;
    background-color: #fff;
    display: flex;
    align-items: center;
  }

  .infoPop {
    width: 500px;
    position: absolute;
    color: #6a6a6a;
    z-index: 99;
    left: 50%;
    top: 30%;
    background: #fff;
    border-radius: 2px;
    border: 1px solid #dadada;
    border-top: 30px solid #039ca8;

    .dit {
      display: flex;
      justify-content: space-between;
      background: #e2f2f3;
      line-height: 32px;
      // padding: 0 10px;

      .time {
        font-size: 12px;
      }
    }

    .close {
      position: absolute;
      right: 10px;
      top: -20px;
      font-size: 14px;
      cursor: pointer;
      color: #fff;
      opacity: 1;
    }

    .title-name {
      position: absolute;
      left: 10px;
      top: -24px;
      font-size: 14px;
      cursor: pointer;
      color: #fff;
      opacity: 1;
    }

    .package {
      margin: 0 auto;

      .left {
        position: relative;

        p {
          margin: 0;
        }

        .title {
          color: #fff;
          position: absolute;
          left: 15px;
          top: -20px;
        }

        .form {
          padding: 0 15px;
          margin: 15px 0;

          .row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 8px;

            /* border-bottom: 1px solid #E5E5E5; */
            .text {
              font-size: 13px;
              line-height: 20px;
              width: 50%;
              padding-left: 15px;

              .el-button {
                background-color: #039ca8;
                color: #fff;
                margin: 10px 0;
              }
            }
          }
        }
      }
    }
  }

  .el-aside {
    margin: 10px 20px 10px 0;
    padding: 0;
  }
  .el-main {
    height: 100%;
    margin: 10px 0 10px 20px;
    padding: 0;
  }
  .el-aside {
    margin-right: 0;
  }
  .el-container {
    height: 98%;
  }
  #cesiumContainer {
    width: 100%;
    height: calc(100% - 230px);
    position: relative;
    overflow: hidden;

    .tree {
      position: absolute;
      right: 0;
      bottom: 0;
      z-index: 996;
      transition: all 0.6s ease 0s;
      width: 12%;
      height: 210px;
      background-color: rgba(84, 92, 100, 0.7);

      .tree-item {
        padding: 0 15px;
        margin: 13px 0;
        display: flex;
        justify-content: space-between;

        .item-col {
          display: inline-block;
          width: 13px;
          height: 13px;
        }
      }

      /* overflow-y: scroll; */
      .treeSc {
        height: 100%;
        overflow-y: scroll;
      }

      .stretchBot {
        text-align: center;
        color: #fff;
        background-color: rgba(84, 92, 100, 0.9);
        cursor: pointer;
        position: absolute;
        top: 0;
        left: -20px;
        width: 20px;
        height: 20px;
        line-height: 20px;

        span {
          font-size: 12px;
        }
      }

      .fw {
        border: none;
      }
    }
  }

  .footer {
    width: 100%;
    height: 170px;
    margin-top: 20px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    overflow: hidden;

    .footer-left {
      width: 84%;
      height: 100%;
      background-color: #fff;
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .left {
        width: 35%;
        height: 100%;
        color: #fff;
        display: flex;
        position: relative;
        justify-content: space-between;
        align-items: flex-start;
        background-color: #096dd9;

        .main {
          width: 100%;
          height: 100%;
          position: relative;
          z-index: 99;

          dd {
            margin: 10px 15px;
          }

          .title {
            font-size: 22px;
            margin-top: 20px;
          }

          .time {
            color: #cecdcd;
            font-size: 14px;
          }

          .value {
            display: inline-block;
            font-size: 35px;
            margin-top: 10px;
            padding: 7px 0;
            color: #615e5d;
            background-color: yellow;
          }

          .grade {
            margin: 5px;
            color: yellow;
          }
        }

        img {
          width: 60%;
          height: 100%;
          position: absolute;
          top: 0;
          right: 0;
          z-index: 9;
        }
      }

      .right {
        width: 65%;
        height: 100%;
        position: relative;
        display: flex;
        justify-content: space-around;
        align-items: center;

        .item {
          width: 12%;
          height: 100%;
          position: relative;

          .echarts {
            width: 100%;
            height: 100%;
          }

          .over-pollutant {
            width: 100px;
            height: 30px;
            text-align: center;
            line-height: 30px;
            position: absolute;
            left: 2px;
            bottom: 10px;
            background-color: red;
            color: #fff;
            border-radius: 5px;
            font-size: 14px;
          }
        }
      }
    }

    .footer-right {
      width: 15%;
      height: 100%;
      margin-left: 30px;
      background-color: #fff;

      dd {
        margin: 5px 0;
        padding: 0 10px;
        display: flex;
        justify-content: space-between;
        align-items: 0;
      }

      img {
        width: 80px;
        height: 60px;
        margin: 20px 80px 0;
      }
    }
  }
}
</style>
